const express = require('express');
const router = express.Router();
const visitorService = require('../services/visitorService');
const { rateLimitMiddleware } = require('../middleware/rateLimit');

// 记录新访问并返回统计数据
router.post('/record', rateLimitMiddleware, async (req, res) => {
  try {
    const stats = await visitorService.recordVisit();
    
    res.json({
      success: true,
      data: stats,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    console.error('Record visit error:', error);
    res.status(500).json({
      success: false,
      error: error.message || '记录访问失败'
    });
  }
});

// 获取访问统计数据
router.get('/stats', rateLimitMiddleware, async (req, res) => {
  try {
    const stats = await visitorService.getVisitStats();
    
    res.json({
      success: true,
      data: stats,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    console.error('Get visit stats error:', error);
    res.status(500).json({
      success: false,
      error: error.message || '获取访问统计失败'
    });
  }
});

module.exports = router;